#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

#include "include/list_node.h"


// 创建
ListNode* ListNodeCreate(int value, ListNode* next) {
    ListNode* node = malloc(sizeof(ListNode));
    node->value = value;
    node->next = next;
    return node; 
} 

// 添加
ListNode* ListNodeAdd(ListNode* head, int value) {
    ListNode* cur = head;
    while (cur->next != NULL) cur = cur->next; 
    cur->next = ListNodeCreate(value, NULL); 
    return head;
} 

// 删除
ListNode* ListNodeRemove(ListNode* head, int value) {
    ListNode* dummyHead = ListNodeCreate(-1, head);
    ListNode* prev = dummyHead; 
    while (prev->next != NULL) {
        // ==> 这里犯了错误，这里应该判断的是prev->next->value == value
        if (prev->next->value == value) {
            ListNode* delNode = prev->next;
            prev->next = delNode->next;
            //delNode->next = NULL; // 不必要的语句
            free(delNode);
            continue;
        }
        prev = prev->next;
    }
    ListNode* retNode = dummyHead->next;
    printf("释放ListNode{value:%d, next:%p}\n", dummyHead->value, dummyHead->next);
    free(dummyHead);
    return retNode; 
}
// 判断
int ListNodeContains(ListNode* head, int value) {
    ListNode* cur = head;
    while (cur != NULL) {
        if (cur->value == value) return 1;
        cur = cur->next; 
    }
    return -1;
} 

// 打印
void ListNodeString(ListNode* head) {
    ListNode* cur = head;
    while (cur != NULL) {
        printf("%d->", cur->value);
        cur = cur->next;
    }
    printf("NULL\n");
}

// 销毁 
void ListNodeDestory(ListNode* head) {
    while (head != NULL) {
        ListNode* node = head; 
        head = head->next; 
        printf("释放ListNode{value:%d, next:%p}\n", node->value, node->next);
        free(node);
    }
} 

